<template>
  <div class="app-container">
    <el-input v-model="listQuery.sociaty_no" clearable placeholder="请输入公会号" style="width:200px"></el-input>
    <el-input v-model="listQuery.search" clearable placeholder="请输入公会名称" style="width:200px"></el-input>
    <el-select v-model="listQuery.status" filterable placeholder="请选择状态">
      <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-select v-model="listQuery.type" filterable placeholder="请选择类别">
      <el-option v-for="item in optionsLevel" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-button icon="el-icon-search" type="primary" @click="getList">搜索</el-button>

    <!--    <div class="filter-container" style="margin-top:10px;">-->
    <el-button class="filter-item" icon="el-icon-plus" type="primary" @click="handleCreate()">
      添加
    </el-button>
    <!--    </div>-->

    <el-table :data="menuList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" border row-key="id"
              style="margin-bottom: 20px;margin-top: 10px;"
    >
      <el-table-column label="公会号" prop="sociaty_no"></el-table-column>
      <el-table-column label="公会名称" prop="sociaty_name"></el-table-column>
      <el-table-column label="描述" prop="description"></el-table-column>
      <el-table-column label="创建时间" prop="add_time"></el-table-column>
      <el-table-column label="公会头像" prop="avatar">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover" width="420">
            <img :src="scope.row.avatar" alt="" style="max-width: 400px;max-height: 400px">
            <img slot="reference" :src="scope.row.avatar" alt="" style="width: 50px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="父级编号" prop="parent_id"></el-table-column>
      <el-table-column label="admin_id" prop="admin_id"></el-table-column>
      <el-table-column label="类别" prop="type">
        <template slot-scope="scope">
          {{ scope.row.type === 1 ? '公会' : '' }}
          {{ scope.row.type === 2 ? '厅' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="关系" prop="relations">
        <template slot-scope="scope">
          {{ scope.row.relations === 0 ? '未挂靠' : '' }}
          {{ scope.row.relations === 1 ? '直属' : '' }}
          {{ scope.row.relations === 2 ? '挂靠' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '正常' : '' }}
          {{ scope.row.status === 2 ? '封禁' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="用户ID" prop="user_id"></el-table-column>
      <el-table-column label="房间编号" prop="room_id"></el-table-column>
      <el-table-column label="直属厅上限" prop="toplimit"></el-table-column>
      <el-table-column label="操作" min-width="320">
        <template slot-scope="scope">
          <!--          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>-->
          <!--            编辑-->
          <!--          </el-button>-->
          <el-button plain size="mini" type="primary" @click="getDetail(scope.row)">公会详情</el-button>
          <el-button plain size="mini" type="primary" @click="setToplimit(scope.row)">直属厅上限</el-button>
          <el-button plain size="mini" type="primary" @click="dismiss(scope.row)">解散工会</el-button>
          <!--          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total" @pagination="getList"/>
    <!--    v-show="total>0"-->

    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose"
    >
      <el-form ref="dataForm" :model="form" :rules="rules" label-position="right" label-width="120px"
               style="width: 400px; margin: 0 auto;"
      >
        <el-form-item label="公会名称" prop="sociaty_name">
          <el-input v-model="form.sociaty_name" maxlength="50" placeholder="公会名称" show-word-limit/>
        </el-form-item>
        <el-form-item label="公会描述">
          <el-input v-model="form.description" maxlength="200" placeholder="公会描述" show-word-limit/>
        </el-form-item>
        <el-form-item label="公会号" prop="sociaty_no">
          <el-input v-model="form.sociaty_no" placeholder="公会号(6位数字)"/>
        </el-form-item>
        <el-form-item label="用户ID" prop="user_id">
          <el-input v-model="form.user_id" placeholder="用户ID"/>
        </el-form-item>
        <el-form-item label="公会logo" prop="avatar">
          <span>{{ form.avatar ? form.avatar.name : '' }}</span>
          <el-upload
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDrag :visible.sync="dialogFormVisible2" title="公会详情" @close="handleDialogClose2">
      <el-form :model="form2" label-position="right" label-width="120px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="管理员姓名：">{{ form2.admin_name }}</el-form-item>
        <el-form-item label="管理员账号：">{{ form2.admin_account }}</el-form-item>
        <el-form-item label="初始密码：">{{ form2.password }}（密码仅第一次有效）</el-form-item>
        <el-form-item label="公会登录地址："><a :href="form2.sociaty_url" style="color:#7BADFF;white-space: nowrap;"
                                         target="_blank"
        >{{ form2.sociaty_url }}</a>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="dialogFormVisible2 = false">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDrag :visible.sync="dialogFormVisible3" title="编辑公会直属厅上限" @close="handleDialogClose3">
      <el-form ref="dataForm3" :model="form3" label-position="right" label-width="120px"
               style="width: 400px; margin: 0 auto;"
      >
        <el-form-item label="上限数值" prop="limit">
          <el-input-number v-model="form3.limit" :min="1" label="上限数值"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible3 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm3()">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDrag :visible.sync="dialogFormVisible4" title="公会详情" @close="handleDialogClose4">
      <el-form :model="form4" label-position="right" label-width="120px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="公会名称：">{{ form4.sociaty_name }}</el-form-item>
        <el-form-item label="公会号：">{{ form4.sociaty_no }}</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="dialogFormVisible4 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm4()">
          解散
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  cacheMenu,
  deleteMenu,
  dismiss,
  getDetail,
  saveMenu,
  setToplimit,
  treeMenu,
  updateMenu
} from '@/api/union/union'

import treeTable from '@/components/TreeTable'
import { validateCh } from '@/utils/validate'

// 常量title
const tempDesc = {
  'id': '',
  'parentId': '',
  'menu_key': '菜单key值',
  'menu_name': '名称',
  'level': '排序',
  'icon': '图标',
  'type': '类型',
  'status': '状态',
  'parent_id': '上级菜单'
}
export default {
  components: { treeTable },
  data() {
    const _validateCh = (rule, value, callback) => {
      if (!!value && validateCh(value)) {
        callback(new Error('不能包含中文'))
      }
      callback()
    }
    return {
      expandAll: false,
      // expandAll: true, // 是否全部展开
      expandAllTitle: '展开全部',
      tempDesc: tempDesc,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      columns: [
        {
          label: '菜单名称',
          key: 'title',
          width: 220,
          expand: true,
          align: 'left',
          headerAlign: 'center'
        },
        {
          label: '菜单key值',
          key: 'menu_key'
        },
        {
          label: tempDesc.type,
          key: 'type'
        },
        {
          label: '状态',
          key: 'status'
        },
        {
          label: tempDesc.icon,
          key: 'icon'
        },
        {
          label: '菜单层级',
          key: 'level'
        }
      ],
      menuList: [],
      menuTree: [],// 树形菜单
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogFormVisible4: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      form: {
        'sociaty_name': undefined,
        'description': undefined,
        'sociaty_no': undefined,
        'user_id': undefined,
        'avatar': undefined
      },
      form2: {
        'admin_name': undefined,
        'admin_account': undefined,
        'password': undefined,
        'sociaty_url': undefined
      },
      form3: {
        'sociaty_id': undefined,
        'limit': undefined
      },

      form4: {
        'admin_name': undefined,
        'admin_account': undefined
      },
      optionsStatus: [{ value: undefined, label: '全部状态' }, { value: '1', label: '正常' }, { value: '2', label: '封禁' }],
      optionsLevel: [{ value: undefined, label: '全部类别' }, { value: '1', label: '公会' }, { value: '2', label: '厅' }],
      rules: {
        sociaty_name: [
          { required: true, message: '请输入公会名称', trigger: 'blur' }
        ],
        sociaty_no: [
          { required: true, message: '请输入公会号', trigger: 'blur' },
          { len: 6, message: '公会号必须为6位', trigger: 'blur' }
        ],
        user_id: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '请输入公会logo', trigger: 'blur' }
        ]
      },
      rules3: {
        limit: [
          { required: true, message: '请输入上限次数', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.search) {
        urlData = urlData + `&search=${this.listQuery.search}`
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`
      }
      if (this.listQuery.sociaty_no) {
        urlData = urlData + `&sociaty_no=${this.listQuery.sociaty_no}`
      }
      if (this.listQuery.type) {
        urlData = urlData + `&type=${this.listQuery.type}`
      }

      treeMenu(urlData).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total

        this.listLoading = false
      })
    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

    },
    getDetail(row) {
      // this.dialogFormVisible = true
      let that = this
      getDetail(row.sociaty_id).then(response => {
        that.form2 = response.data
        that.dialogFormVisible2 = true
      })
    },
    setToplimit(row) {
      this.dialogFormVisible3 = true
      this.form3.sociaty_id = row.sociaty_id
      this.form3.limit = row.toplimit
    },
    dismiss(row) {
      this.dialogFormVisible4 = true
      this.form4.sociaty_name = row.sociaty_name
      this.form4.sociaty_no = row.sociaty_no
      this.form4.sociaty_id = row.sociaty_id
    },
    handleUpdate(row) {
      this.form = []
      // this.form = Object.assign({}, row) // copy obj  此方法在这里暂时不能使用，会出错 -> 有多余参数
      this.form.sociaty_name = row.sociaty_name
      this.form.description = row.description
      this.form.sociaty_no = row.sociaty_no
      this.form.user_id = row.user_id
      this.form.avatar = row.avatar

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      let parentNode = this.findTreeNode(row.parentId)
      if (parentNode) {
        this.form.parent_id = parentNode.menu_name
      }

      this.form = Object.assign({}, this.form)
    },
    handleDelete(row) {
      deleteMenu(row.id).then(response => {
        if (response.code === 0) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        }
      })
    },
    submitForm() {
      // this.form.parent_id = undefined;
      this.$refs['dataForm'].validate(valid => {
        let formData = new FormData()
        for (let item in this.form) {
          this.form[item] === undefined ? '' : formData.append(item, this.form[item])
        }
        if (valid && this.dialogStatus === 'create') {
          saveMenu(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              })
            }
          })
        } else if (valid && this.dialogStatus === 'update') {
          updateMenu(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              })
            }
          })
        }
      })
    },
    submitForm3() {
      // this.form.parent_id = undefined;
      this.$refs['dataForm3'].validate(valid => {
        let formData = new FormData()
        for (let item in this.form3) {
          this.form3[item] === undefined ? '' : formData.append(item, this.form3[item])
        }
        setToplimit(formData).then(response => {
          if (response.code === 200) {
            this.getList()
            this.$notify({
              type: 'success',
              message: '操作成功',
              position: 'bottom-right',
              showClose: false,
              duration: 3000
            })
            this.dialogFormVisible3 = false
          } else {
            this.$message({
              message: response.message,
              type: 'error'
            })
          }
        })
      })
    },
    submitForm4() {
      let formData = { sociaty_id: this.form4.sociaty_id }
      dismiss(formData).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
          this.dialogFormVisible4 = false
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })

    },
    cache() {
      cacheMenu(this.form).then(response => {
        this.$notify({
          type: 'success',
          message: '操作成功',
          position: 'bottom-right',
          showClose: false,
          duration: 3000
        })
      })
    },
    findTreeNode(id) {
      let node = this._.find(this.menuList, { id: parseInt(id) })
      return node
    },
    handleExpand() {
      this.expandAll = !this.expandAll
      this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
    },
    resetForm() {
      this.form = {
        'sociaty_name': undefined,
        'description': undefined,
        'sociaty_no': undefined,
        'user_id': undefined,
        'avatar': undefined
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    },
    handleDialogClose2() {
    },
    handleDialogClose3() {
    },
    handleDialogClose4() {
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      this.form.avatar = file
    }
  }
}
</script>
